'use strict'

const Command = require('@pengsg-cli/command')
const Package = require('@pengsg-cli/package')
const log = require('@pengsg-cli/log')
const request = require('@pengsg-cli/request')
const { loadingSpinners } = require("@pengsg-cli/util");
const fs = require('fs')
const path = require('path')
const inquirer = require('inquirer')
const fse = require('fs-extra')
const semver = require('semver')
const userHome = require('user-home')
const TYPE = {
  project: 'project',
  component: 'component',
}

class InitCommand extends Command {
  init() {
    this.projectName = this._argv[0]
    // console.log(this._cmd)
    // this.force = this._cmd.force;
    log.verbose(this.projectName)
    log.verbose(this.force)
  }
  async exec() {
    // 1,准备阶段
    const projectInfo = await this.prepare()
    this.projectInfo = projectInfo
    log.verbose('projectInfo', projectInfo)
    // 2,下载阶段 
    await this.downloadTemplate()
    // 3,安装阶段
  }

  async prepare() {
    // 判断模版是否存在
    const templeData = await this.getNpmTemple()
    log.verbose('templateInfo', templeData)
    if (!templeData || templeData.length === 0) {
      throw new Error('项目模版不存在')
    }
    this.templateInfo = templeData
    // 判断当前目录是否为空
    const currentPath = process.cwd()
    if (!this.isCWDEmpty(currentPath)) {
      // 询问是否清空
      const { ifContiue } = await inquirer.prompt({
        type: 'confirm',
        name: 'ifContiue',
        default: false,
        message: '需要清空当前目录,是否继续?',
      })
      if (ifContiue) {
        // 确认是否清空
        const { ifConfirm } = await inquirer.prompt({
          type: 'confirm',
          name: 'ifConfirm',
          default: false,
          message: '确认是否清空?',
        })
        if (ifConfirm) {
          // 开始清空目录
          fse.emptyDirSync(currentPath)
        } else {
          return
        }
      } else {
        return
      }
    }
    return this.getProjectInfo()
    // 开始获取项目基本信息
  }

  async getProjectInfo() {
    const { type } = await inquirer.prompt({
      type: 'list',
      name: 'type',
      message: '请选择类型',
      choices: [
        {
          name: '项目',
          value: TYPE.project,
        },
        {
          name: '组件',
          value: TYPE.component,
        },
      ],
    })
    if (type === TYPE.project) {
      // 获取项目的基本信息
      let projectInfo = await inquirer.prompt([
        {
          type: 'input',
          name: 'projectName',
          default: '',
          message: '请输入项目名称',
          validate: function (v) {
            const done = this.async()
            setTimeout(function () {
              if (
                !/^[a-zA-Z]+([_][a-zA-Z0-9]|[-][a-zA-Z0-9]|[a-zA-Z0-9])*[a-zA-Z]$/.test(
                  v,
                )
              ) {
                done('请输入合乎规定的项目名称')
                return
              }
              done(null, true)
            }, 0)
          },
          filter: function (v) {
            return v
          },
        },
        {
          type: 'input',
          name: 'projectVersion',
          message: '请输入项目版本号',
          default: '1.0.0',
          validate: function (v) {
            const done = this.async()
            setTimeout(function () {
              if (!semver.valid(v)) {
                done('请输入合乎规定的版本号')
                return
              }
              done(null, true)
            }, 0)
          },
          filter: function (v) {
            if (!!semver.valid(v)) {
              return semver.valid(v)
            } else {
              return v
            }
          },
        },
        {
          type: 'list',
          name: 'templateName',
          message: '请选择项目模版',
          choices: this.getNpmTempleChoice(),
        },
      ])
      return {
        type,
        ...projectInfo,
      }
    } else {
      // 获取组件相关信息
    }
  }

  isCWDEmpty(currentPath) {
    let currentFileList = fs.readdirSync(currentPath)
    currentFileList = currentFileList.filter(
      (file) => !file.startsWith('.') && file !== 'node_modules',
    )
    return !currentFileList || currentFileList.length === 0
  }

  async getNpmTemple() {
    return await request({
      url: '/project/getTemple',
      methods: 'get',
    })
  }

  getNpmTempleChoice() {
    return this.templateInfo.map(({ templateName, npmName }) => {
      return {
        name: templateName,
        value: npmName,
      }
    })
  }

  async downloadTemplate() {
    console.log({
      templateInfo: this.templateInfo,
      projectInfo: this.projectInfo,
    })
    // 获取用户选择的项目及模版信息
    const packageInfo = this.templateInfo.find(
      (item) => item.npmName === this.projectInfo.templateName,
    )
    // 根据模版信息初始化Package类
    const { npmName: packageName, npmVersion: packageVersion } = packageInfo
    const targetPath = path.resolve(userHome, process.env.CLI_HOME)
    const storePath = path.join(targetPath, 'node_modules')
    const packages = new Package({
      targetPath,
      storePath,
      packageName,
      packageVersion,
    })
    if (await packages.exist()) {
      try {
        loadingSpinners().start()
        await packages.update()
      } catch (error) {
        // log.error('更新失败',error)
        // throw error
      }finally{
        loadingSpinners().stop()
      }
      
    } else {
      try {
        loadingSpinners().start()
        await packages.install()
        
      } catch (error) {
        // log.error('下载失败',error)
        // throw error
      }finally{
        loadingSpinners().stop()
      }
    }
  }
}

function init(argv) {
  return new InitCommand(argv)
}

module.exports = init
module.exports.InitCommand = InitCommand
